import React, { useState, useEffect } from 'react';
import { Card, Table, DatePicker, Select, Input, Button, Space, Tag, Tooltip, Drawer, Descriptions, Timeline, Typography, Badge } from 'antd';
import { SearchOutlined, HistoryOutlined, UserOutlined, FilterOutlined, ExportOutlined, EyeOutlined } from '@ant-design/icons';
import { useAuditLogStore, AuditLog } from '../../stores/auditLogStore';
import LogFilterPanel from './LogFilterPanel';
import dayjs from 'dayjs';
import { Key } from 'react';

const { RangePicker } = DatePicker;
const { Text } = Typography;
const { Option } = Select;

const AuditLogViewer: React.FC = () => {
  const { logs, loading, fetchLogs } = useAuditLogStore();
  const [selectedLog, setSelectedLog] = useState<AuditLog | null>(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [showFilters, setShowFilters] = useState(false);
  
  useEffect(() => {
    fetchLogs();
  }, [fetchLogs]);
  
  // 处理查看详情
  const handleViewDetails = (log: AuditLog) => {
    setSelectedLog(log);
    setDrawerVisible(true);
  };
  
  // 处理导出日志
  const handleExportLogs = () => {
    // 实际项目中可以实现导出功能
    console.log('导出日志');
  };
  
  // 获取状态标签颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case '成功':
        return 'success';
      case '失败':
        return 'error';
      case '警告':
        return 'warning';
      default:
        return 'default';
    }
  };
  
  // 获取事件类型标签颜色
  const getEventTypeColor = (eventType: string) => {
    switch (eventType) {
      case '登录':
        return 'blue';
      case '文档创建':
        return 'green';
      case '文档更新':
        return 'orange';
      case '文档删除':
        return 'red';
      case '系统配置':
        return 'purple';
      default:
        return 'default';
    }
  };
  
  // 表格列定义
  const columns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      sorter: (a: AuditLog, b: AuditLog) => 
        dayjs(a.timestamp).valueOf() - dayjs(b.timestamp).valueOf(),
      render: (timestamp: string) => dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '用户',
      dataIndex: 'username',
      key: 'username',
      render: (username: string, record: AuditLog) => (
        <Space>
          <UserOutlined />
          {username}
        </Space>
      ),
    },
    {
      title: '事件类型',
      dataIndex: 'eventType',
      key: 'eventType',
      filters: [
        { text: '登录', value: '登录' },
        { text: '文档创建', value: '文档创建' },
        { text: '文档更新', value: '文档更新' },
        { text: '文档删除', value: '文档删除' },
        { text: '系统配置', value: '系统配置' },
      ],
      onFilter: (value: boolean | Key, record: AuditLog) => 
        record.eventType === value,
      render: (eventType: string) => (
        <Tag color={getEventTypeColor(eventType)}>{eventType}</Tag>
      ),
    },
    {
      title: '资源类型',
      dataIndex: 'resourceType',
      key: 'resourceType',
      filters: [
        { text: '用户', value: '用户' },
        { text: '文档', value: '文档' },
        { text: '模型', value: '模型' },
        { text: '系统', value: '系统' },
      ],
      onFilter: (value: boolean | Key, record: AuditLog) => 
        record.resourceType === value,
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      filters: [
        { text: '成功', value: '成功' },
        { text: '失败', value: '失败' },
        { text: '警告', value: '警告' },
      ],
      onFilter: (value: boolean | Key, record: AuditLog) => 
        record.status === value,
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>{status}</Tag>
      ),
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'operation',
      width: 100,
      render: (_: any, record: AuditLog) => (
        <Button 
          type="text"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetails(record)}
        >
          查看
        </Button>
      ),
    },
  ];
  
  return (
    <div style={{ display: 'flex', gap: 16, flexDirection: showFilters ? 'row' : 'column' }}>
      {showFilters && (
        <div style={{ width: 300, flexShrink: 0 }}>
          <LogFilterPanel />
        </div>
      )}
      
      <div style={{ flexGrow: 1 }}>
        <Card
          title="操作日志"
          extra={(
            <Space>
              <Button 
                icon={<FilterOutlined />} 
                onClick={() => setShowFilters(!showFilters)}
              >
                {showFilters ? '隐藏筛选' : '显示筛选'}
              </Button>
              <Button 
                icon={<ExportOutlined />}
                onClick={handleExportLogs}
              >
                导出
              </Button>
            </Space>
          )}
        >
          <Table
            columns={columns}
            dataSource={logs}
            rowKey="id"
            pagination={{ pageSize: 15 }}
            loading={loading}
          />
        </Card>
      </div>
      
      <Drawer
        title="日志详情"
        placement="right"
        width={500}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
      >
        {selectedLog && (
          <>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="时间">
                {dayjs(selectedLog.timestamp).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
              <Descriptions.Item label="用户">
                {selectedLog.username}
              </Descriptions.Item>
              <Descriptions.Item label="事件类型">
                <Tag color={getEventTypeColor(selectedLog.eventType)}>
                  {selectedLog.eventType}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="资源类型">
                {selectedLog.resourceType}
              </Descriptions.Item>
              <Descriptions.Item label="资源ID">
                {selectedLog.resourceId}
              </Descriptions.Item>
              <Descriptions.Item label="操作">
                {selectedLog.action}
              </Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={getStatusColor(selectedLog.status)}>
                  {selectedLog.status}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="IP地址">
                {selectedLog.ipAddress}
              </Descriptions.Item>
              <Descriptions.Item label="详情">
                {selectedLog.details}
              </Descriptions.Item>
            </Descriptions>
            
            <div style={{ marginTop: 24 }}>
              <Text strong>操作时间线</Text>
              <Timeline style={{ marginTop: 16 }}>
                <Timeline.Item>用户访问系统 - {dayjs(selectedLog.timestamp).subtract(2, 'minute').format('HH:mm:ss')}</Timeline.Item>
                <Timeline.Item>
                  <Badge status={selectedLog.status === '成功' ? 'success' : selectedLog.status === '失败' ? 'error' : 'warning'} />
                  执行{selectedLog.action}操作 - {dayjs(selectedLog.timestamp).format('HH:mm:ss')}
                </Timeline.Item>
              </Timeline>
            </div>
          </>
        )}
      </Drawer>
    </div>
  );
};

export default AuditLogViewer; 